package com.aixingfu.sports.Https;

import android.content.Context;
import android.util.Log;

import com.aixingfu.sports.Model.StateModel;
import com.alibaba.android.arouter.launcher.ARouter;
import com.orie.librarybase.BaseApplication;
import com.orie.librarybase.net.CookieUtils.CookieManger;
import com.orie.librarybase.net.HttpConfig;
import com.vondear.rxtool.view.RxToast;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author : 吕冬冬
 * Time : 2018\12\26 0011
 * Description : https请求封装处理
 */
public class NetHome {

    private static HomeApi api;
    public static long DEFAULT_TIMEOUT = 30;
    private static File httpCacheDirectory;
    private static Cache cache = null;

    public static HomeApi getApi(Context context) {
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("ddong",message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new MyInterceptor())
                .addInterceptor(loggingInterceptor)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 这里你可以根据自己的机型设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
                .build();

        if (api == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(HttpConfig.BASEURL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            api = retrofit.create(HomeApi.class);
        }
        return api;
    }
    public static HomeApi getLoginApi(Context context) {
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("ddong",message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieManger(context))
                .addInterceptor(loggingInterceptor)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 这里你可以根据自己的机型设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
                .build();

        if (api == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(HttpConfig.BASEURL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            api = retrofit.create(HomeApi.class);
        }
        return api;
    }

    public static HomeApi getApiWithCache(Context context) {

        if (httpCacheDirectory == null) {
            httpCacheDirectory = new File(context.getCacheDir(), "WithCache_cache");
        }

        try {
            if (cache == null) {
                cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
            }
        } catch (Exception e) {
            Log.e("OKHttp", "Could not create http cache", e);
        }

        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("dd",message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieManger(context))
                .cache(cache)
               .addNetworkInterceptor(loggingInterceptor)
                //.addNetworkInterceptor(new CaheInterceptor(context))
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 这里你可以根据自己的机型设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
                .build();

        if (api == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(HttpConfig.BASEURL)
//                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            api = retrofit.create(HomeApi.class);
        }

        return api;
    }



    /**
     * 再封装一层，统一处理未登录等情况
     *
     * @param data
     * @param listener
     * @param <T>
     */
    public static <T> void loadData(Observable<T> data, final NetListener<T> listener) {

        data.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<T>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(T t) {
//                        Log.i("获取到的json ", "onNext: " + new Gson().toJson(t));
//                        listener.onSuccess(t);
                      if (((StateModel) t).getCode() == -1) {
                            //未登录
                            listener.onFailed(((StateModel) t).getCode(), "登录已过期,请重新登录");
                            RxToast.normal(BaseApplication.getContext(),((StateModel) t).getMessage()).show();
                            ARouter.getInstance().build("/main/LoginActivity").withBoolean("isLogout", true).navigation();

                        } else if (((StateModel) t).getCode() == 1) {
                            //成功
                            listener.onSuccess(t);
                        } else {
                            //其他错误信息
//                            listener.onFailed(((StateModel) t).getCode(), ((StateModel) t).msg);
                            listener.onSuccess(t);
                        }

                    }
                    @Override
                    public void onError(Throwable e) {
                        //请求不上，可能是网络问题
                        Log.i("NetSchool日志", "onError: " + e.getLocalizedMessage());
                        listener.onFailed(-2, "网络请求失败，请稍后再试");
//                        listener.onComplete();
                    }

                    @Override
                    public void onComplete() {
                        listener.onComplete();
                    }
                });
    }
}
